package com.fivefu.core.gb28181.listner.impl;

import com.alibaba.fastjson.JSON;
import com.fivefu.core.gb28181.listner.SipRequestListener;
import com.fivefu.core.gb28181.listner.SipServerLayer;
import com.fivefu.core.gb28181.utils.EncryptUtils;
import com.fivefu.core.gb28181.utils.SipMessageUtils;
import gov.nist.javax.sip.RequestEventExt;
import gov.nist.javax.sip.address.AddressImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.address.URI;
import javax.sip.header.*;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.UUID;

@Component
public class RegisterListener implements SipRequestListener {

    @Autowired
    private SipServerLayer sipServerLayer;
    @Autowired
    private SipMessageUtils sipMessageUtils;

    @Override
    public void process(RequestEvent requestEvent) throws SipException, ParseException, InvalidArgumentException {
        RequestEventExt ext = (RequestEventExt) requestEvent;
        System.out.println("收到注册请求：" + ext.getRemoteIpAddress() + ":" + ext.getRemotePort());
        Request request = ext.getRequest();
        FromHeader fromRequest = (FromHeader) request.getHeader(FromHeader.NAME);
        AddressImpl fromAddress = (AddressImpl) fromRequest.getAddress();
        SipURI sipURI = (SipURI) fromAddress.getURI();
        String deviceId = sipURI.getUser();

//        String deviceType = null;
//        ListIterator viaHeaders = request.getHeaders(ViaHeader.NAME);
//        while (viaHeaders.hasNext()){
//            ViaHeader viaHeader = (ViaHeader) viaHeaders.next();
//            deviceType = viaHeader.getTransport();
//        }

        Response response = null;
        MessageFactory messageFactory = sipServerLayer.getSipFactory().createMessageFactory();

        ExpiresHeader expiresHeader = (ExpiresHeader) request.getHeader(ExpiresHeader.NAME);
        int expireTime = expiresHeader.getExpires();
        if (expireTime == 0){//超时
            response = messageFactory.createResponse(Response.BAD_REQUEST, request);
        }else{
            AuthorizationHeader authorhead = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
            // 校验密码是否正确
            if (authorhead != null) {
                response = messageFactory.createResponse(Response.OK, request);
                response.setHeader(request.getHeader(ContactHeader.NAME));

            }else{
                WWWAuthenticateHeader wwwAuthorizationHeader = sipServerLayer.getSipFactory().createHeaderFactory().createWWWAuthenticateHeader("Digest");
//                wwwAuthorizationHeader.setParameter("realm","192.168.0");//域名
//                wwwAuthorizationHeader.setParameter("nonce", UUID.randomUUID().toString());//任意或非重复的随机数值
//                wwwAuthorizationHeader.setParameter("algorithm","MD5");//加密方式
//                wwwAuthorizationHeader.setParameter("qop","auth");

                wwwAuthorizationHeader.setParameter("username","admin");//域名
                wwwAuthorizationHeader.setParameter("realm","3402000000");//设备编号
                //wwwAuthorizationHeader.setParameter("realm","34020000001180000001");//设备编号
                wwwAuthorizationHeader.setParameter("nonce", EncryptUtils.md5("Fivefu@123"));//加密后的密码
                wwwAuthorizationHeader.setParameter("algorithm","MD5");//加密方式
                wwwAuthorizationHeader.setParameter("uri","sip:192.168.0.138:5060");

                response = messageFactory.createResponse(Response.UNAUTHORIZED, request);
                response.addHeader(wwwAuthorizationHeader);
            }
        }

        sipMessageUtils.ackRequest(requestEvent, response);

        System.out.println(expiresHeader.getExpires());


    }

    @Override
    public void afterPropertiesSet() throws Exception {
        sipServerLayer.addSipListener(Request.REGISTER,this);
    }
}
